package com.mezz.bones.framework.core.helper;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@RequiredArgsConstructor
@Slf4j
public class EnvironmentHelper implements CommandLineRunner {

    private final Environment env;
    public void printConfiguration(String[] args) {
        // 打印激活的Profile
        String[] activeProfiles = env.getActiveProfiles();
        System.out.println("\n=== 激活的Profiles ===");
        System.out.println(activeProfiles.length > 0 ?
                String.join(",", activeProfiles) : "default");

        // 打印所有配置源信息
        System.out.println("\n=== 配置源列表 ===");
        ((AbstractEnvironment) env).getPropertySources().forEach(propertySource -> {

            String propertySourceName = propertySource.getName();
            List<String> ignorePropertySources = ignorePropertySourceList();
            if((ignorePropertySources.contains(propertySourceName))){
                log.debug("忽略配置源: {}", propertySourceName);
                return;
            }

            System.out.println("\n▸ 配置源名称: " + propertySource.getName());

            if (propertySource instanceof EnumerablePropertySource) {
                EnumerablePropertySource<?> enumerable = (EnumerablePropertySource<?>) propertySource;
                Arrays.stream(enumerable.getPropertyNames())
                        .filter(key -> !isSensitiveKey(key))
                        .forEach(key -> {
                            Object value = enumerable.getProperty(key);
                            System.out.printf("   %-40s = %s%n",
                                    key, maskSensitiveValue(key, value));
                        });
            } else {
                System.out.println("   (非可枚举配置源)");
            }
        });

        // 打印启动参数
        System.out.println("\n=== 启动参数 ===");
        Arrays.stream(args).forEach(arg -> System.out.println("-- " + arg));
    }

    private static List<String> ignorePropertySourceList() {

        return Stream.of("systemProperties","systemEnvironment").collect(Collectors.toList());
    }

    // 敏感字段检测
    private static boolean isSensitiveKey(String key) {
        String lowerKey = key.toLowerCase();
        return lowerKey.contains("password") ||
                lowerKey.contains("secret") ||
                lowerKey.contains("key") ||
                lowerKey.contains("token");
    }

    // 敏感信息脱敏
    private static Object maskSensitiveValue(String key, Object value) {
        if (value == null) return null;
        if (isSensitiveKey(key)) {
            String str = value.toString();
            if (str.length() <= 4) return "****";
            return str.substring(0, 2) + "****" + str.substring(str.length()-2);
        }
        return value;
    }

    @Override
    public void run(String... args) throws Exception {
        printConfiguration(args);
    }
}
